#include "TransformRotator.hpp"
#include "MathHelper.hpp"

using namespace Typhoon;

TransformRotator::TransformRotator() {
	input = 0;
	isRotating = false;
	xAngle = 0;
	yAngle = 0;
	Speed = 0.002f;

	MaxPitch = ToRadians(89);
}

TransformRotator::~TransformRotator() {
	if (input) {
		input->Down -= event_handler(this, &TransformRotator::Down);
		input->Up -= event_handler(this, &TransformRotator::Up);
	}
}

void TransformRotator::SetInputManager( InputManager* input )
{
	this->input = input;
	input->Down += event_handler(this, &TransformRotator::Down);
	input->Up += event_handler(this, &TransformRotator::Up);
}


void TransformRotator::Down( InputManager::EventData event )
{
	if (event.Index!=1) return;

	startPosition = event.Position;
	isRotating = true;
}

void TransformRotator::Up( InputManager::EventData event )
{
	if (event.Index!=1) return;
	isRotating = false;

	Vector2 delta = input->GetPosition(1) - startPosition;

	xAngle = xAngle - delta.y * Speed;
	yAngle = yAngle - delta.x * Speed;

	if (xAngle<-MaxPitch) {
		xAngle = -MaxPitch;
	} else if (xAngle>MaxPitch) {
		xAngle = MaxPitch;
	}
}

void TransformRotator::Update(float dt) {
	if (!isRotating) { return; }

	Vector2 delta = input->GetPosition(1) - startPosition;

	GameObjects& list = GetGameObjects();

	for (GameObjects::iterator it = list.begin(); it!=list.end(); ++it) {
		Transform* transform = (*it)->GetComponent<Transform>();

		float xRot = xAngle - delta.y * Speed;
		float yRot = yAngle - delta.x * Speed;

		if (xRot<-MaxPitch) {
			xRot = -MaxPitch;
		} else if (xRot>MaxPitch) {
			xRot = MaxPitch;
		}
		
		Quaternion xAxis = Quaternion::Create(xRot, Vector3(1,0,0));
		Quaternion yAxis = Quaternion::Create(yRot, Vector3(0,1,0));

		Quaternion rot = yAxis * xAxis;

		transform->Rotation = rot;
	}
}
